package org.wen.soft.asm.model;

import lombok.Data;
import org.wen.soft.asm.AsmLoad;
import org.wen.soft.util.FileUtil;
import org.wen.soft.util.StrCastUtil;

import java.util.ArrayList;
import java.util.List;

@Data
public class LoadClass {
    String fileName;

    // visit
    int version;
    int access;
    String name;
    String signature;
    String superName;
    String[] interfaces;
    // source
    String source;
    String debug;


    List<LoadAnnotation> loadAnnotations = new ArrayList<>();
    List<LoadField> loadFields = new ArrayList<>();
    List<LoadMethod> loadMethods = new ArrayList<>();
    List<LoadInnerClass> loadInnerClassesInfo = new ArrayList<>();
    List<LoadClass> loadInnerClasses = new ArrayList<>();


    public LoadClass() {
    }

    public void visit(int version, int access, String name, String signature, String superName, String[] interfaces) {
        this.version = version;
        this.access = access;
        this.name = name;
        this.signature = signature;
        this.superName = superName;
        this.interfaces = interfaces;
    }

    public void visitSource(String source, String debug){
        this.source = source;
        this.debug = debug;
    }

    public void visitAnnotation(LoadAnnotation loadAnnotation) {
        loadAnnotations.add(loadAnnotation);
    }

    public void visitField(LoadField loadField) {
        loadFields.add(loadField);
    }

    public void visitMethod(LoadMethod loadMethod) {
        loadMethods.add(loadMethod);
    }

    public void visitInnerClass(LoadInnerClass loadInnerClass) {
        if (fileName == null) {
            return;
        }
        loadInnerClassesInfo.add(loadInnerClass);
        String outerName = StrCastUtil.pathToPath(loadInnerClass.getOuterName());
        String innerName = StrCastUtil.pathToPath(loadInnerClass.getName());

        String outerFile = StrCastUtil.pathToPath(fileName);
        if (outerFile.contains(outerName) && !outerFile.contains(innerName)) {
            String innerClassFile = outerFile.replace(outerName, innerName);
            if (FileUtil.exists(innerClassFile)) {
                loadInnerClasses.add(AsmLoad.loadClass(innerClassFile));
            }
        }
    }
}
